﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PetkaWebDav.Server.Framework.BaseClasses;
using Microsoft.WindowsAzure.Storage.Blob;

namespace CloudStorageLight.Core.WebDav.Handlers
{
    /// <summary>
    /// Custom implementation example for DavUnlock.
    /// </summary>
    public sealed class DavUnlock : DavUnlockBase
    {
        public DavUnlock()
        {
        }

        protected override async Task OnProcessDavRequest(EventArgs e)
        {
            //Check to see if a lock already exists
            //CloudBlockBlob _lockFile = RequestWrapper.GetLockFileByLockToken(base.LockToken);

            //if (_lockFile == null)
             var blob = (BlobFile)await RequestWrapper.GetRequestFile();

             if (blob != null && blob.Metadata.ContainsKey("OpaqueLock") && blob.Metadata["OpaqueLock"] == null)
             {
                 base.AbortRequest(DavUnlockResponseCode.PreconditionFailed);
             }
             else
             {
                 //RequestWrapper.DeleteAzureFile(_lockFile.Name);
                 blob.OpaqueLock = null;
                 blob.CheckOutUserId = null;
                 blob.LockTimeout = null;
                 blob.LockOwner = null;
                 await blob.SetMetadataAsync();
             }
        }
    }
}
